package com.example.everying.utils;/*
 * 项目名称: everything
 * 文件名: AliVideoModerationUtil
 * 作者: 张泽阳
 * 日期: 2025/7/25
 * 描述:
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.*;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

import static java.lang.Thread.sleep;

@Component
@Slf4j
public class AliVideoModerationUtil {
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.green.regionId}")
    private String regionId;

    @Value("${aliyun.green.endpoint}")
    private String endpoint;

    @Value("${aliyun.green.read-timeout:6000}")
    private int readTimeout;

    @Value("${aliyun.green.connect-timeout:3000}")
    private int connectTimeout;

    private Client client;

    @PostConstruct
    public void init() throws Exception {
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(accessKeySecret);
        config.setRegionId(regionId);
        config.setEndpoint(endpoint);
        config.setReadTimeout(readTimeout);
        config.setConnectTimeout(connectTimeout);
        this.client = new Client(config);
    }

    public boolean checkVideo(String videoUrl) {
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("url",videoUrl);

        VideoModerationRequest videoModerationRequest = new VideoModerationRequest();
        // 检测类型：videoDetection
        videoModerationRequest.setService("videoDetection");
        videoModerationRequest.setServiceParameters(serviceParameters.toJSONString());

        try {
            VideoModerationResponse response = client.videoModeration(videoModerationRequest);
            if (response.getStatusCode() == 200) {
                VideoModerationResponseBody result = response.getBody();
                System.out.println(JSON.toJSONString(result));
                System.out.println("requestId = " + result.getRequestId());
                System.out.println("code = " + result.getCode());
                System.out.println("msg = " + result.getMessage());
                Integer code = result.getCode();
                if (200 == code) {
                    VideoModerationResponseBody.VideoModerationResponseBodyData data = result.getData();
                    System.out.println("taskId = " + data.getTaskId() );
                    VideoModerationResultResponse videoResponse = getCheckResult(data.getTaskId());
                    if (videoResponse.getStatusCode() == 200){
                        VideoModerationResultResponseBody videoResult = videoResponse.getBody();
                        int count = 0;
                        while (videoResult.getCode() == 280 && count++ <= 240){
                            sleep(500);
                            videoResult = getCheckResult(data.getTaskId()).getBody();
                        }
                        VideoModerationResultResponseBody.VideoModerationResultResponseBodyData resultData = getCheckResult(data.getTaskId()).getBody().getData();
                        String jsonString = JSON.toJSONString(resultData);
                        JSONObject obj = (JSONObject)JSON.parse(jsonString);
                        if (obj.getString("riskLevel") == null){
                            log.warn("视频审核失败");
                            return false;
                        }
                        if (!obj.getString("riskLevel").equals("high")){
                            return true;
                        }else {
                            return false;
                        }

                    }else {
                        log.info("response not success. status: {}" , response.getStatusCode());
                    }
                } else {
                    log.info("video moderation not success. code: {}" , code);
                }
            } else {
                log.info("response not success. status: {}" , response.getStatusCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public VideoModerationResultResponse getCheckResult(String taskId) throws Exception {
        JSONObject serviceParameters = new JSONObject();
        // 提交任务时返回的taskId。
        serviceParameters.put("taskId", taskId);


        VideoModerationResultRequest videoModerationResultRequest = new VideoModerationResultRequest();
        // 检测类型：videoDetection
        videoModerationResultRequest.setService("videoDetection");
        videoModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());
        return  client.videoModerationResult(videoModerationResultRequest);
    }
}
